package cn.kgcnews.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.kgcnews.pojo.PageBean;
import cn.kgcnews.pojo.User;
import cn.kgcnews.service.UserService;
import cn.kgcnews.service.impl.UserServiceImpl;

public class SerchUserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;


	public void destroy() {
		super.destroy(); 
	}


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		int currentPageNo=1;//当前页码
		int pageSize=2;//一页显示条数
		String queryName="";//查询用户姓名
		int roleId=-1;//查询用户类型
		int totalPageCount=0;//总页数
		queryName=request.getParameter("queryUserName");
		String name=queryName;
		String type=request.getParameter("queryUserType");
		System.out.println("接收到的username"+queryName);
		System.out.println("接收到的usertype"+type);
		if(queryName!=null&&!"".equals(queryName)){
			queryName="%"+queryName+"%";
		}
		String pageNo=request.getParameter("pageno");
		if(pageNo!=null&&!"".equals(pageNo)){
			currentPageNo=Integer.valueOf(pageNo);
		}
		if(type!=null&&!"".equals(type)){
			roleId=Integer.valueOf(type);
		}
	
		
		UserService us =new UserServiceImpl();
		
		totalPageCount=us.queryTotalPageCount(pageSize, queryName, roleId);
		System.out.println("总页数又是："+totalPageCount);
		if(totalPageCount!=0){
		if(currentPageNo==0){
			currentPageNo=1;
		}
		if(currentPageNo>=totalPageCount){
			currentPageNo=totalPageCount;
		}
		PageBean<User> pagebean = us.queruserByPageno(currentPageNo, pageSize, queryName, roleId);
		queryName=name;//取出“%” 不然后面的查询会出现%重叠
		//将pagebean放入session作用域内
		HttpSession session=request.getSession();
		System.out.println("总页码为："+pagebean.getTotalPageCount());
		System.out.println("总查询数量为："+pagebean.getTotalCount());
		session.setAttribute("bean", pagebean);
		session.setAttribute("queryUserName", queryName);
		session.setAttribute("queryUserType", type);
		response.sendRedirect("userlist.jsp");//重定向方法跳转网页
		}else{
			out.println("<script>alert('错误');location.href='serchuser';</script>");
		}
		out.flush();
		out.close();
	}

	public void init() throws ServletException {
		
	}

}
